package com.bckj.fastboot.core.rpc.feign;


import com.bckj.fastboot.core.jackson.JsonUtils;
import com.bckj.fastboot.core.lang.exception.BusinessException;
import com.bckj.fastboot.core.lang.exception.SystemException;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.Collection;

public class ExceptionErrorDecoder implements ErrorDecoder {
    public ExceptionErrorDecoder() {
    }

    public Exception decode(String methodKey, Response feignResponse) {
        Collection<String> strings = (Collection)feignResponse.headers().get("abc");
        if (strings != null && !strings.isEmpty() && strings.contains("default")) {
            try {
                if (feignResponse.body() != null) {
                    byte[] bytes = Util.toByteArray(feignResponse.body().asInputStream());
                    Object responseError = JavaSerialization.deserialize(bytes);
                    if ("HystrixBadRequestException".equals(responseError.getClass().getSimpleName())) {
                        int code = 100000;
                        String message = "";

                        try {
                            Method method = responseError.getClass().getMethod("getStatus");
                            code = (Integer)method.invoke(responseError);
                            Method method2 = responseError.getClass().getMethod("getMessage");
                            message = (String)method2.invoke(responseError);
                        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException var10) {
                        }

                        return new BusinessException(code, message);
                    }
                }
            } catch (IOException var11) {
            }

            return new SystemException("feign 反序列化异常出错");
        } else {
            try {
                String body = Util.toString(feignResponse.body().asReader(StandardCharsets.UTF_8));
                ExceptionResponse exceptionResponse = JsonUtils.toBean(body, ExceptionResponse.class);
                exceptionResponse.setCode(100000);
                Class<?> exceptionClass = Class.forName(exceptionResponse.getException());
                Constructor<?> constructor = exceptionClass.getConstructor(String.class);
                Object o = constructor.newInstance(exceptionResponse.getMessage());
                if (o instanceof BusinessException) {
                    ((BusinessException)o).setCode(exceptionResponse.getCode());
                }

                return (Exception)o;
            } catch (Exception var12) {
                return (new ErrorDecoder.Default()).decode(methodKey, feignResponse);
            }
        }
    }
}
